/*
 * Buffer.h
 *
 *  Created on: 2011-5-29
 *      Author: yangentao@gmail.com
 */

#ifndef BUFFER_H_
#define BUFFER_H_
#include "../pre.h"

//可替代数组, 用于基本类型,自动释放内存
template<typename T>
class Buffer {
public:
	explicit Buffer(T* buf = 0, size_t len = 0, bool copy = false) {
		setBuffer(buf, len, copy);
	}
	virtual ~Buffer();
public:
	inline void setBuffer(T* buf, size_t len, bool copy = true) {
		if (len <= 0) {
			length = 0;
			return;
		}
		length = len;
		if (copy) {
			buffer.reset(new T[length]);
			memcopy(buffer.get(), buf, length * sizeof(T));
		} else {
			buffer.reset(buf);
		}
	}
	inline void resize(size_t newSize, bool copy = true) {
		if (newSize == 0) {
			buffer.reset(nullptr);
			length = 0;
			return;
		}
		if (copy) {
			if(length > newSize){
				length = newSize;
			}else{
				T* buf = new T[newSize];
				memcopy(buf, buffer.get(), length* sizeof(T));
				memset(buf + length, 0, newSize - length);
				buffer.reset(buf);
				length = newSize;
			}
		} else {
			length = newSize;
			buffer.reset(new T[length]);
		}

	}

	inline T operator [](size_t index) {
		assert(index < length);
		return buffer[index];
	}
	inline operator T*() {
		return buffer.get();
	}
	inline T* get() {
		return buffer.get();
	}
	inline int size() {
		return length;
	}
	inline void clear() {
		length = 0;
		buffer.reset(0);
	}
private:
	boost::shared_array<T> buffer;
	size_t length;
};

#endif /* BUFFER_H_ */
